import axios from 'axios';

/**
 * 请求取消策略类（策略模式）
 */
export class CancelStrategy {
  private pendingRequests = new Map<string, () => void>();

  /**
   * 处理取消逻辑
   * @param config 请求配置
   * @param cancelable 是否启用取消功能
   * @param method 请求方法
   * @param url 请求地址
   */
  handleCancelableRequest(config: any, cancelable: boolean, method: string, url: string) {
    if (cancelable) {
      config.cancelToken = new axios.CancelToken((cancel) => {
        const key = `${method}:${url}`;
        if (this.pendingRequests.has(key)) {
          const cancelFn = this.pendingRequests.get(key);
          cancelFn && cancelFn(); // 取消之前的请求
        }
        this.pendingRequests.set(key, cancel); // 记录当前请求
      });
    }
  }

  /**
   * 移除记录
   * @param method 请求方法
   * @param url 请求地址
   */
  removeRequest(method: string, url: string) {
    const key = `${method}:${url}`;
    this.pendingRequests.delete(key);
  }
}
